package com.material.c2c.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 读取配置文件
 * @Description: TODO()
 * @author: wt
 * @date: 2016年5月24日 下午3:40:55
 * @最后修改人: wt
 * @最后修改时间: 2016年5月24日 下午3:40:55
 * @JDK version:  jdk1.6 
 * @version V1.0
 * @copyright: 四川凯普顿信息技术有限公司
 */
public class PropertiesUtil {

	private static final Logger logger = LogManager.getLogger(PropertiesUtil.class);
	
	private String filePath = null;
	private Properties p = null;
	
	public enum ReadType {
		CACHE("cache"),	 // 缓存
		RELATIVE_PATH("relativePath"), 	// 相对路径
		ABSOLUTE_PATH("absolutePath");		// 绝对路径
		private String value;
		ReadType(String value) {
			this.value = value;
		}
		public String getValue() {
			return value;
		}
	}
	
	public PropertiesUtil(String fileName) {
		initProperty(fileName, ReadType.CACHE);	//1.缓存获取 推荐 fileName="/datasource.properties"
		//initProperty(fileName, ReadType.RELATIVE_PATH);//2.相对路径	  fileName="/datasource.properties"
		//initProperty(fileName, ReadType.ABSOLUTE_PATH);//3.绝对路径	  fileName="D:/datasource.properties"
	}

	public PropertiesUtil(String fileName, ReadType type) {
		initProperty(fileName, type);
	}
	
	/**
	 * 初始化配置文件
	 * @Description: TODO()
	 * @param fileName
	 * @param type
	 */
	private void initProperty(String fileName, ReadType type){
		try {
			p = new Properties();
			FileInputStream in = null;
			if (type == ReadType.CACHE) {
				//1.缓存获取 推荐
				if (!fileName.startsWith("/")) fileName = "/" + fileName;
				p.load(PropertiesUtil.class.getResourceAsStream(fileName));
				String path = PropertiesUtil.class.getResource(fileName).getPath().toString().replaceAll("%20", " ");// 类路径
				this.filePath = path;
			} else if (type == ReadType.RELATIVE_PATH) {
				//2.相对路径
				if (!fileName.startsWith("/")) fileName = "/" + fileName;
				String path = PropertiesUtil.class.getResource(fileName).getPath().toString().replaceAll("%20", " ");// 类路径
				this.filePath = path;
				in = new FileInputStream(new File(path));
				p.load(in);
			} else if (type == ReadType.ABSOLUTE_PATH) {
				//3.完整路径
				this.filePath = fileName;
				in = new FileInputStream(new File(fileName));
				p.load(in);
			}
			if (in != null) in.close();
		} catch (FileNotFoundException e) {
			logger.error("找不到配置文件:" + fileName, e);
		} catch (IOException e) {
			logger.error("读取配置文件错误:" + fileName, e);
		}
	}

	/**
	 * 设置配置
	 * @Description: TODO()
	 * @param key
	 * @return
	 */
	public String getProperty(String key) {
		return p.getProperty(key);
	}

	/**
	 * 读取配置
	 * @Description: TODO()
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public String getProperty(String key, String defaultValue) {
		return p.getProperty(key, defaultValue);
	}

	/**
	 * UTF-8编码 读取配置文件格式为UTF-8编码的中文
	 * @Description: TODO()
	 * @param key
	 * @return
	 */
	public String getPropertyCN(String key) {
		try {
			return new String(p.getProperty(key).getBytes("Latin1"), "utf-8");// 读取utf-8编码文件
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * UTF-8编码 读取配置文件格式为GBK编码的中文
	 * @Description: TODO()
	 * @param key
	 * @return
	 */
	public String getPropertyGBK(String key) {
		try {
			return new String(p.getProperty(key).getBytes("Latin1"), "GBK");// 读取GBK编码文件
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public void saveFile() throws Exception {
		if (filePath == null && filePath.length() == 0) {
			throw new Exception("需指定保存的配置文件名");
		}
		saveFile(filePath);
	}
	
	public void saveFile(String filepath) throws Exception {
		saveFile(filepath, "");
	}
	
	/**
	 * 保存配置文件
	 * @Description: TODO()
	 * @param filepath
	 * @param description
	 * @throws Exception
	 */
	public void saveFile(String filepath, String description) throws Exception {
		try {
			FileInputStream in = null;
			FileOutputStream out = null;
			File f = new File(filepath);
			out = new FileOutputStream(f);
			p.store(out, description);
			out.close();
		} catch (IOException ex) {
			throw new Exception("无法保存指定的配置文件:" + filepath);
		}
	}

	public Properties getPropertys() {
		return p;
	}

	public void put(String key, String value) {
		p.put(key, value);
	}

	public void remove(String key) {
		p.remove(key);
	}

	public void setProperty(String key, String value) {
		p.setProperty(key, value);
	}

	public void list() {
		p.list(System.out);
	}

	public static void main(String args[]) {
		//PropertiesUtil p = new PropertiesUtil("datasource.properties",1);
		//PropertiesUtil p = new PropertiesUtil("/datasource.properties",1);
		PropertiesUtil p = new PropertiesUtil("d:/datasource.properties", ReadType.ABSOLUTE_PATH);
		System.out.println(p.getProperty("name"));
		System.out.println(p.getPropertyCN("name"));
		System.out.println(p.getPropertyGBK("name"));
		p.list();//列出所有配置
		try {
			//修改配置文件
			p.setProperty("name", "中文测试");
			p.saveFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
